<?php

class Webmix_AjaxController extends Core_Controller_Action_Standard
{
    public function loadcontentAction(){
        $webmix_id = $this->_getParam('webmix_id',0);
        if(empty($webmix_id)) return;
        $webmix = Engine_Api::_()->getItem('webmixes',$webmix_id);
        $blockTable = Engine_Api::_()->getDbtable('blocks','webmix');
        $blocks = $blockTable->getBlocks($webmix_id);
        $result = array();
        $backgound = Engine_Api::_()->getApi('settings','core')->getSetting('webmix.block.background','white');
        $color = Engine_Api::_()->getApi('settings','core')->getSetting('webmix.block.color','#CCCCCC');
        foreach($blocks as $block){
            $title = '';
            if(empty($block->photo_id)) $title = $block->title;
            $a = array('block_id'=>$block->block_id,'block_name'=>$title,'photo'=>$block->getPhotoUrl('thumb.normal'),'link'=>$block->link,'row'=>$block->position_x,'col'=>$block->position_y,'company_id'=>$block->company_id,'owner'=>$block->company_owner,'backgound'=>$backgound,'color'=>$color,'company_approve'=>$block->isCompanyApproved()            );
            if (isset($block->key)) $a['key'] = $block->key;
            else $a['key'] = '';
            $result[] = $a;
        }
        $this->view->blocks = $result;
        $this->view->type = $webmix->type;
        $this->view->parent = $webmix->parent_id;
        $this->view->isdefault = $webmix->default;
        $this->view->content_type = $webmix->content_type;
        
        $viewer = Engine_Api::_()->user()->getViewer();
        $webmixTable = Engine_Api::_()->getDbtable('webmixes','webmix');
        $select = $webmixTable->select()
                              ->where('owner_id = ?',$viewer->user_id)
                              ->where('parent_id = ?',$webmix_id);
        $row = $webmixTable->fetchRow($select);
        if($row) {
            if(!empty($row->default)) $this->view->isdefault = 1;
        }                         
    }
    public function rssAction(){
        $url = $this->_getParam('url','http://news.google.com/?output=rss');
        $cacheid = md5('webmix_google_rss');
        $cache = Zend_Registry::get('Zend_Cache');
        $data = $cache->load($cacheid);
        $cacheTimeout = 900;
        if(empty($data) || !is_array($data)){
            $data = null;
        }
        else {
            if(time()> $data['fetched'] + $cacheTimeout){
                $data = null;
            }
        }
        if(!$data){
            $xml = simplexml_load_file($url);
            $items  = $xml->channel->item;
            
            $data = array();
    		
            foreach($items as $item){
    			$data['item'][] = array(
    				'title'=>(string)$item->title,
    				'link'=>(string)$item->link,
    				'time'=> date('H:s',strtotime($item->pubDate))
    			);
                
            }
            $data['fetched'] = time();
            $cache->save($data, $cacheId);
        }
        
        $this->view->data = $data;
         
        
    }
    
    public function savetabAction(){
        $viewer = Engine_Api::_()->user()->getViewer();
        if(empty($viewer) || empty($viewer->user_id)) {
            $this->view->error = true;
            return;
        }
        $order = $this->_getParam('order',array());
        if(empty($order)){
            $this->view->error = true;
            return;
        }
        $webmixTable = Engine_Api::_()->getDbtable('webmixes','webmix');
        foreach($order as $key => $value){
            $webmixTable->update(
                array('order'=>$key),
                array('webmix_id = ?'=> $value)
            );
        }
        $this->view->error = false;
        return;
        
    }
    
    public function renderwebmixAction(){
        $webmix_id = $this->_getParam('webmix_id');
        $this->view->webmix_id = $webmix_id;
    }

    public function clickcountAction(){
        $webmix_id = $this->_getParam('webmix_id',0);
        $company_id = $this->_getParam('company');
        if (empty($webmix_id)) {
            
            $company = Engine_Api::_()->getItem('webmix_company',$company_id);
            $company->click_count = $company->click_count + 1;
            $company->save();
        }
        else {
            $webmix = Engine_Api::_()->getItem('webmixes',$webmix_id);
            if ($webmix->content_type == Webmix_Api_Core::WEBMIX_CONTENT_TYPE_MUSIC){
                $company = Engine_Api::_()->getItem('webmix_musicalbum',$company_id);
            }
            else {
                $company = Engine_Api::_()->getItem('webmix_company',$company_id);
            }
            $company->click_count = $company->click_count + 1;
            $company->save();
            
        }
        return;
    } 

  public function getCompanyAction(){
    $name = $this->_getParam('name');
    $id = $this->_getParam('id');
    $action_type = $this->_getParam('action_type');
    $viewer = Engine_Api::_()->user()->getViewer();
    if(!$name && !$id){
        return;
    }
    
    $content_type = $this->_getParam('content_type');
    if ($content_type == 'music'){
        $webmix_id = $this->_getParam('webmix_id',0);
        if (empty($webmix_id)) {
            return;
        }
        
        $albumTable = Engine_Api::_()->getDbTable('musicalbums','webmix');
        //$blockIns = $albumTable->getCompanyIDbyWebmix($webmix_id);
        $select = $albumTable->select()
                             ->where('title like ?',$name.'%');
                            // ->where('musicalbum_id not in (?)',$blockIns);
                             
        $album = $albumTable->fetchAll($select)->toArray();
        return $this->_helper->json($album);
       
    }
    $Company_table = Engine_Api::_()->getDbTable('companies','webmix');     
    //get Hint by company title
    if($name && $name != ""){
        $Country_table = Engine_Api::_()->getDbTable('countries','webmix');   
                
        $select = $Company_table->select()
                    ->setIntegrityCheck(false)
                    ->from('engine4_webmix_companies as company')
                    ->join('engine4_webmix_countries as country', 'country.country_id = company.country_id',array('country_id','key'))
                    ->where('company.title like ?',$name.'%')
                    ->where('country.selected = 1')
                    ;  
         
        if($action_type == 'edit'){
            //user can only edit own company   
            $select->where('owner_id = ? AND company.approve = 0',$viewer->getIdentity());
        }
        else{
            //Admin Or Onwer not Approved Or Approved of other users
            //$select->where('(owner_id = ? AND company.approve = 0) OR (company.approve = 1 AND owner_id <> ?)',$viewer->getIdentity());
            
            //not duplicate db when approve 
            $select->where('owner_id = ? OR company.approve = 1 ',$viewer->getIdentity());                        
        }
        
    }
    //get company (to fill) by company_id
    $companies = array();
    if($id){

        $select = $Company_table->select()
                    ->where('company_id = ?',$id.'%');
        $row = $Company_table->fetchAll($select)->getRow(0);
        
        $photo_url = $row->getPhotoUrl('thumb.normal');        
        
        $companies = array(
            'photo_url' => $photo_url,
        );                              
    }
                                            
    // if get company by id
   	$companies = array_merge($Company_table->fetchAll($select)->toArray(), $companies);     
    
    return $this->_helper->json($companies);
    $this->getResponse()->setBody(Zend_Json::encode($companies));
  } 
  
  public function locationAction(){
        $location = $this->_getParam('lo','New York');
        
        $cacheid = md5('webmix_google_location'.$location);
        $cache = Zend_Registry::get('Zend_Cache');
        $data = $cache->load($cacheid);
        $cacheTimeout = 900;
        if(empty($data) || !is_array($data)){
            $data = null;
        }
        else {
            if(time()> $data['fetched'] + $cacheTimeout){
                $data = null;
            }
        }
        
        if($data && is_array($data) && count($data) > 0){
            $this->view->locations = $data;
            return;
        }
        
        $xml = simplexml_load_file('http://api.wunderground.com/auto/wui/geo/GeoLookupXML/index.xml?query=' . urlencode($location));
        
        $result = array();
        /*foreach($xml as $a){
            
            $result[] = (string)$a->name;
        }*/
        $result[] = (string)$xml->city;
        $this->view->locations = $result;
        
        $result['fetched'] = time();
        $cache->save($result, $cacheId);
        
  } 
  
  public function weatherAction(){
        $viewer = Engine_Api::_()->user()->getViewer();
        $location = $this->_getParam('lo','New York');
        $webmix_id = $this->_getParam('webmix_id',0);
        $webmix = Engine_Api::_()->getItem('webmixes',$webmix_id);
        if($webmix){
            if($viewer->user_id == $webmix->owner_id || $viewer->isAdmin()){
                $webmix->location = $location;
                $webmix->save();
            }
            
        }
        $cacheid = md5('webmix_google_weather'.$location);
        $cache = Zend_Registry::get('Zend_Cache');
        $data = $cache->load($cacheid);
        $cacheTimeout = 900;
        if(empty($data) || !is_array($data)){
            $data = null;
        }
        else {
            if(time()> $data['fetched'] + $cacheTimeout){
                $data = null;
            }
        }
        if($data){
            $this->view->forecast = $data;
            return;
        }
            
        
        
        $type = $this->_getParam('type','C');
       
        $xml = simplexml_load_file('http://api.wunderground.com/auto/wui/geo/ForecastXML/index.xml?query=' . urlencode($location));
   
        $xml = $xml->simpleforecast->forecastday;
        $result = array();
        
        foreach($xml as $day){
            
            if($type == 'C'){
                $result[] = array(
                    
                    'weather' => $day->high->celsius.'-'.$day->low->celsius.' C',
                    'con'=>(string)$day->conditions[0],
                    'icon' => (string)$day->icons->icon_set [0]->icon_url,
                    'day' =>(string)$day->date[0]->weekday
                    
                );
            }
            else {
                $result[] = array(
                    'weather' => $day->high[0]->fahrenheit.'-'.$day->low[0]->fahrenheit.' F',
                    
                    'con'=>(string)$day->conditions,
                    'icon' => (string)$day->icons->icon_set [0]->icon_url,
                    'day' =>(string)$day->date[0]->weekday
                    
                );
            }
            
            $result['fetched'] = time();
            $cache->save($result, $cacheId);
            
        }
        $this->view->forecast = $result;
  }     
}
